package com.stxx.assistant.framwork.utils;

/**
 * @author Fuzhenlei
 * @date 2025/01/15 11:29
 */
public class PermissionUtils {
    private static final char[] c64 = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
    };
    private static final byte[] b64 = new byte[128];
    static {
        for (byte i = 0; i < c64.length; i++) {
            b64[c64[i]] = i;
        }
    }
    //长度决定角色数量的多少，比如长度20，可以有20*6=120个角色
    private static final Integer permissionLen=20;

    public static Integer total(){
        return permissionLen*6;
    }
    public static CharSequence allowAll(){
        StringBuilder sb = new StringBuilder(permissionLen);
        for (int i = 0; i < permissionLen; i++) {
            sb.append(c64[63]);
        }
        return  sb.toString();
    }
    public static CharSequence rejectAll(){
        StringBuilder sb = new StringBuilder(permissionLen);
        for (int i = 0; i < permissionLen; i++) {
            sb.append(c64[0]);
        }
        return sb.toString();
    }

    /**
     * 检查是否有权限
     * @param roleIndex
     * @param permission
     * @return
     */
    public static Boolean check(int roleIndex,CharSequence permission){
        int[] pos = getPos(roleIndex);
        byte a = b64[permission.charAt(pos[0])];
        return (a & (1 << pos[1])) != 0;
    }

    /**
     * 授予访问权限
     * @param roleIndex
     * @param permission
     * @return
     */
    public static String allow(int roleIndex,CharSequence permission){
        int[] pos = getPos(roleIndex);
        StringBuilder sb = new StringBuilder(permission);
        sb.setCharAt(pos[0],c64[b64[permission.charAt(pos[0])]|(1 << pos[1])]);
        return sb.toString();
    }

    /**
     * 拒绝访问权限
     * @param roleIndex
     * @param permission
     * @return
     */
    public static String reject(int roleIndex,String permission){
        int[] pos = getPos(roleIndex);
        StringBuilder sb = new StringBuilder(permission);
        sb.setCharAt(pos[0],c64[b64[permission.charAt(pos[0])]&63^(1 << pos[1])]);
        return sb.toString();
    }
    private static int[] getPos(int roleIndex){
        return new int[]{roleIndex/6,roleIndex%6};
    }
}
